package com.atguigu.tingshu.handler;


import com.atguigu.tingshu.entity.CDCEntity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;


@Component
@CanalTable("album_info")// 指定监听表名
public class CdcEntryHandler implements EntryHandler<CDCEntity> {
    @Autowired
    private StringRedisTemplate redisTemplate;
//    @Autowired
//    private RabbitService rabbitService;

    /**
     * 新增
     *
     * @param cdcEntity 新增实体
     */
    @Override
    public void insert(CDCEntity cdcEntity) {
        EntryHandler.super.insert(cdcEntity);
    }

    /**
     * 修改
     *
     * @param before 修改前实体
     * @param after  修改后实体
     */
    @Override
    public void update(CDCEntity before, CDCEntity after) {
        String cacheKey = getCacheKey(after);
        try {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            redisTemplate.delete(cacheKey);
        } catch (RuntimeException e) {
            // TODO
            // 发送缓存key给rabbitmq 完成重试删除redis逻辑
//            rabbitService.sendMessage(MqConst.EXCHANGE_ALBUM, MqConst.ROUTING_ALBUM_STAT_UPDATE, cacheKey);
        }
    }

    /**
     * 删除
     *
     * @param cdcEntity 删除实体
     */
    @Override
    public void delete(CDCEntity cdcEntity) {
        String cacheKey = getCacheKey(cdcEntity);
        try {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            redisTemplate.delete(cacheKey);
        } catch (RuntimeException e) {
            // TODO
            // 发送缓存key给rabbitmq 完成重试删除redis逻辑
//            rabbitService.sendMessage(MqConst.EXCHANGE_ALBUM, MqConst.ROUTING_ALBUM_STAT_UPDATE, cacheKey);
        }
    }


    private static String getCacheKey(CDCEntity cdcEntity) {
        Long entityId = cdcEntity.getId();
        return "cache:info:" + entityId;
    }
}